window.initImport = function (GM_xmlhttpRequest, userid, marketCode, freightTemplateId, version) {
	'use strict';
	var $ = window.jQuery;
	var freightTemplateIdradio = (freightTemplateId && freightTemplateId !== 'null') ? '3' : '1'
	var alibabaToken = 'nmP4XodkXaGRdSAaE4AMWA==';
	version = version || '3.0';
	var url = 'http://work.yiwugo.com/product_s/alibaba_product_insert.htm';
	var data = new FormData();
	var tmallDetail = null;
	var setSpecialData = {
		'detail.1688.com': {
			setDetail: function (callback) {
				if ($(".mod-detail-easyoffer-dsc").length > 0) {//特殊商品，详情取法与一般商品不同
					callback($(".mod-detail-easyoffer-dsc").html())
				} else if ($('#desc-lazyload-container').attr('data-tfs-url')) {
					GM_xmlhttpRequest({
						method: "get",
						url: $('#desc-lazyload-container').attr('data-tfs-url'),
						onload: function (res) {
							if (res.status !== 200) {
								console.error('获取详情失败', res.status)
							} else {
								var stringJson = res.responseText.replace(/^[^=]+=['"]?(.+)/, '$1').replace(/['";s]+$/, '')
								try {
									var json = JSON.parse(stringJson || '{}');
									callback(json.content)
								} catch (e) {
									callback(stringJson)
								}
							}
						}
					})
				} else if (window.__INIT_DATA){
					var obj = __INIT_DATA.data['1081181309894'] || __INIT_DATA.data['774504306919']
					GM_xmlhttpRequest({
						method: "get",
						url: obj.data.detailUrl,
						onload: function (res) {
							if (res.status !== 200) {
								console.error('获取详情失败', res.status)
							} else {
								var stringJson = res.responseText.replace(/^[^=]+=['"]?(.+)/, '$1').replace(/['";s]+$/, '')
								try {
									var json = JSON.parse(stringJson || '{}');
									callback(json.content)
								} catch (e) {
									callback(stringJson)
								}
							}
						}
					})
				}
			},
			setTitle: function () {
				data.append('title', $("meta[property='og:title']").attr('content') || $('.title-first-column .title-text').html() || $('.title-info .title-info-name').html());
			},
			setMetric: function () {
				var unit = window.iDetailConfig ? iDetailConfig.unit : ''
				if (window.__INIT_DATA){
					var obj = __INIT_DATA.data['1081181309101'] || __INIT_DATA.data['774504306190']
					unit = obj.data.unit
				}
				data.append('metric', unit);
				data.append('customMetric', unit);
			},
			setBeginNumber: function () {
				var beginNumber = window.iDetailConfig ? iDetailConfig.beginAmount : ''
				if (window.__INIT_DATA){
					var obj = __INIT_DATA.data['1081181309101'] || __INIT_DATA.data['774504306190']
					beginNumber = obj.data.startAmount
				}
				data.append('beginNumber', beginNumber || 1);
			},
			setImages: function () {
				if (window.iDetailConfig){
					$("li.tab-trigger").each(function(i) {
						try {
							var jsonObj = $.parseJSON($(this).attr('data-imgs'));
							if (jsonObj) {
								data.append('smallpic' + (i + 1), jsonObj.original);
								if (i == 6) {
									return false;
								}
							}
						} catch (err) {}
					});
				} else if(window.__INIT_DATA) {
					var obj = __INIT_DATA.data['1081181309881'] || __INIT_DATA.data['774504306937']
					$.each(obj.data.offerImgList,function(i){
						data.append('smallpic' + (i + 1), this.toString());
					})
				}
			},
			setPrice: function () {
				if (window.iDetailData){
					if (!iDetailData.hasOwnProperty("sku")) {//判断是否含有sku相关内容
						if ($("tr.price").length > 0) {//分销产品阶梯价 eg：563807493881
							data.append('priceType', '1');
							var i = 0;
							$("tr.price").children().each(function () {//遍历价格
								var range = $(this).attr("data-range");
								if (range) {
									var jsonRange = eval("(" + range + ")");
									data.append('price' + i + '0', jsonRange["begin"]);
									data.append('price' + i + '3', jsonRange["price"]);
									i++;
								}
							});
							//可售总数
							var salenum;
							try {
								var html = $("span.total")[0].innerHTML;
								salenum = html.match(/(?<=（)[0-9]*?(?=[一-龥])/g);//提取以“（”开头，已中文结尾的数字，即可售数量
							} catch (e) {
								salenum = 99999
							}
							data.append('salenum', salenum);
							data.append('perentCheck', '0');
							data.append('perentValue', '规格');//没有规格按照混批处理
							data.append('childValue1', '混批');//没有规格按照混批处理
						} else {//未知类型当作面议处理
							data.append('priceType', '0');
						}
					} else if (iDetailData.sku.hasOwnProperty("priceRange")) {//阶梯价
						data.append('priceType', '1');
						//可售总数
						data.append('salenum', iDetailData.sku.canBookCount);
						//价格设置
						$.each(iDetailData.sku.priceRange, function (index, value, array) {
							data.append('price' + index + '0', value[0]);
							data.append('price' + index + '3', value[1]);
						});
						//购买选项
						if (iDetailData.sku.hasOwnProperty("skuProps")) {
							var sku_props = iDetailData.sku.skuProps;
							var perentCheck = '';
							var perentValue = '';
							for (var i = 0; i < sku_props.length; i++) {
								if (i != 0) {
									perentCheck += ',';
									perentValue += ',';
								} else {
									var child_pic_str = '';
									for (var k = 0; k < sku_props[i].value.length; k++) {
										if (k != 0) {
											child_pic_str += ','
										}
										child_pic_str += sku_props[i].value[k].imageUrl || ''
										if (k == 19) {
											break;
										}
									}
									data.append('childPicture1', child_pic_str);
								}
								perentCheck += i;
								perentValue += sku_props[i].prop;
								var child_value_str = '';
								for (var j = 0; j < sku_props[i].value.length; j++) {
									if (j != 0) {
										child_value_str += ',';
									}
									child_value_str += sku_props[i].value[j].name;
									if (j == 19) {
										break;
									}
								}
								//data+='&childValue'+(i+1)+'='+child_value_str;
								data.append('childValue' + (i + 1), child_value_str);
								if (i == 3) {
									break;
								}
							}
							data.append('perentCheck', perentCheck);
							data.append('perentValue', perentValue);
						}
					} else {//按规格定价
						data.append('priceType', '3');
						var skuMap = iDetailData.sku.skuMap;
						var skuProps = iDetailData.sku.skuProps;
						var picMap = {}
						if (skuProps && skuProps.length && skuProps[0].value) {
							$.each(skuProps[0].value, function (i, item) {
								if (item.imageUrl) {
									picMap[item.name] = item.imageUrl
								}
							});
						}
						var property_value_list = [];
						var index = 0;
						$.each(skuMap, function (i) {
							if (index > 49) {
								return false
							}
							index++
							property_value_list.push({
								'property': i.replace('&gt;', '：').replace(',', '，').replace('(', '（').replace('<', '《').replace(')', '）').replace('>', '》').replace('?', '？').replace(/[\\\&]/, ''),
								'price': skuMap[i].discountPrice,
								'stock': skuMap[i].canBookCount,
								'picture': picMap[i.split('&gt;')[0]] || ''
							})
						});
						var temp = "[{\"name\": \"\", \"values\":" + JSON.stringify(property_value_list) + "}]"
						data.append('sellPropertyJson', temp);
					}
				} else if (window.__INIT_DATA){
					try{
						var obj = __INIT_DATA.data['1081181309884']
						var offerDomain = JSON.parse(obj.data.offerDomain)

						if (offerDomain.tradeModel.disPriceRanges){
							data.append('priceType', '1') //阶梯价
							//可售总数
							data.append('salenum', offerDomain.tradeModel.canBookedAmount);
							//价格设置
							$.each(offerDomain.tradeModel.disPriceRanges, function (index, value, array) {
								data.append('price' + index + '0', this.beginAmount);
								data.append('price' + index + '3', this.price);
							});
							//购买选项
							if(offerDomain.offerDetail.skuProps){
								var sku_props = offerDomain.offerDetail.skuProps
								var perentCheck = '';
								var perentValue = '';
								for (var i = 0; i < sku_props.length; i++) {
									if (i != 0) {
										perentCheck += ',';
										perentValue += ',';
									} else {
										var child_pic_str = '';
										for (var k = 0; k < sku_props[i].value.length; k++) {
											if (k != 0) {
												child_pic_str += ','
											}
											child_pic_str += sku_props[i].value[k].imageUrl || ''
											if (k == 19) {
												break;
											}
										}
										data.append('childPicture1', child_pic_str);
									}
									perentCheck += i;
									perentValue += sku_props[i].prop;
									var child_value_str = '';
									for (var j = 0; j < sku_props[i].value.length; j++) {
										if (j != 0) {
											child_value_str += ',';
										}
										child_value_str += sku_props[i].value[j].name;
										if (j == 19) {
											break;
										}
									}
									//data+='&childValue'+(i+1)+'='+child_value_str;
									data.append('childValue' + (i + 1), child_value_str);
									if (i == 3) {
										break;
									}
								}
								data.append('perentCheck', perentCheck);
								data.append('perentValue', perentValue);
							}
						} else if (__INIT_DATA.globalData.skuModel){
							var skuModel = __INIT_DATA.globalData.skuModel
							data.append('priceType', '3') //按规格定价
							var skuMap = skuModel.skuInfoMap;
							var skuProps = skuModel.skuProps;
							var picMap = {}
							if (skuProps && skuProps.length && skuProps[0].value) {
								$.each(skuProps[0].value, function (i, item) {
									if (item.imageUrl) {
										picMap[item.name] = item.imageUrl
									}
								});
							}
							var property_value_list = [];
							var index = 0;
							$.each(skuMap, function (i) {
								if (index > 49) {
									return false
								}
								index++
								property_value_list.push({
									'property': i.replace('&gt;', '：').replace(',', '，').replace('(', '（').replace('<', '《').replace(')', '）').replace('>', '》').replace('?', '？').replace(/[\\\&]/, ''),
									'price': skuMap[i].discountPrice,
									'stock': 999999,
									'picture': picMap[i.split('&gt;')[0]] || ''
								})
							});
							var temp = "[{\"name\": \"\", \"values\":" + JSON.stringify(property_value_list) + "}]"
							data.append('sellPropertyJson', temp);
						}
					} catch (e){
						var skuModel = __INIT_DATA.globalData.skuModel
						if(skuModel.skuProps){
							data.append('priceType', '3') //按规格定价
							var skuMap = skuModel.skuInfoMap;
							var skuProps = skuModel.skuProps;
							var picMap = {}
							if (skuProps && skuProps.length && skuProps[0].value) {
								$.each(skuProps[0].value, function (i, item) {
									if (item.imageUrl) {
										picMap[item.name] = item.imageUrl
									}
								});
							}
							var property_value_list = [];
							var index = 0;
							$.each(skuMap, function (i) {
								if (index > 49) {
									return false
								}
								index++
								property_value_list.push({
									'property': i.replace('&gt;', '：').replace(',', '，').replace('(', '（').replace('<', '《').replace(')', '）').replace('>', '》').replace('?', '？').replace(/[\\\&]/, ''),
									'price': skuMap[i].discountPrice,
									'stock': 999999,
									'picture': picMap[i.split('&gt;')[0]] || ''
								})
							});
							var temp = "[{\"name\": \"\", \"values\":" + JSON.stringify(property_value_list) + "}]"
							data.append('sellPropertyJson', temp);
						} else {
							data.append('priceType', '1') //阶梯价
							data.append('salenum', 99999999);
							data.append('price00', __INIT_DATA.globalData.processingModel.customTradeAttributes.beginAmount);
							data.append('price03', __INIT_DATA.globalData.processingModel.customTradeAttributes.minPrice);
						}
					}
				}

			},
			appendToSelector: '.unit-detail-order-action'
		},
		'item.taobao.com': {
			setDetail: function (callback) {
				GM_xmlhttpRequest({
					method: "get",
					url: /^https/.test(g_config.descUrl) ? g_config.descUrl : 'https:' + g_config.descUrl,
					onload: function (res) {
						if (res.status !== 200) {
							console.error('获取详情失败')
						} else {
							var stringJson = res.responseText.replace(/^[^=]+=['"]?(.+)/, '$1').replace(/['";s]+$/, '')
							try {
								var json = JSON.parse(stringJson || '{}');
								callback(json.content)
							} catch (e) {
								callback(stringJson)
							}
						}
					}
				})
			},
			setTitle: function () {
				var title = ''
				try {
					title = data.append('title', g_config.idata.item.title);
				} catch (e) {
					console.error('获取title失败', e)
				}
				data.append('title', title);
			},
			setMetric: function () {
				data.append('metric', '件');
			},
			setBeginNumber: function () {
				data.append('beginNumber', 1);
			},
			setImages: function () {
				try {
					$.each(g_config.idata.item.auctionImages, function (index, item) {
						data.append('smallpic' + (index + 1), /^http/.test(item) ? item : 'http:' + item);
						if (index === 4) {
							return false
						}
					})
				} catch (e) {
					console.error('获取图片失败', e)
				}
			},
			setPrice: function () {
				//淘宝默认按规格
				data.append('priceType', '3');
				var property_value_list = [];
				var dataValueMap = {}
				try {
					var index = 0
					$.each(g_config.sibRequest.data.originalPrice, function (key, item) {
						if (index > 49) {
							return false
						}
						index++
						var propertys = []
						var pictrue = ''
						var isLegal = true
						$.each(key.split(';'), function (index, id) {
							if (id) {
								if (!dataValueMap[id]) {
									dataValueMap[id] = $("[data-value='" + id + "']")
								}
								if (dataValueMap[id].length) {
									propertys.push(dataValueMap[id].find('a').find('span').text())
									if (dataValueMap[id].find('a').css('backgroundImage') && dataValueMap[id].find('a').css('backgroundImage').match(/http[^"]+/) && dataValueMap[id].find('a').css('backgroundImage').match(/http[^"]+/).length) {
										pictrue = dataValueMap[id].find('a').css('backgroundImage').match(/http[^"]+/)[0]
									}
								} else {
									return isLegal = false
								}
							}
						})
						isLegal && property_value_list.push({
							'property': propertys.toString().replace(/,/g, '：'),
							'price': item.price,
							'stock': g_config.sibRequest.data.dynStock.sku[key] ? g_config.sibRequest.data.dynStock.sku[key].stock : 0,
							'picture': pictrue
						})
					})
					var temp = "[{\"name\": \"\", \"values\":" + JSON.stringify(property_value_list) + "}]"
					data.append('sellPropertyJson', temp);
				} catch (e) {
					console.error('获取价格失败', e)
				}
			},
			appendToSelector: '.tb-btn-add'
		},
		'detail.tmall.com': {
			setDetail: function (callback) {
				$('script').each(function () {
					var matcher = $(this).text().match(/(?<=TShop\.Setup\(\n)[^\n]+(?=\n)/)
					if (matcher && matcher.length) {
						tmallDetail = JSON.parse(matcher[0])
						return false
					}
				})
				GM_xmlhttpRequest({
					method: "get",
					url: /^http/.test(tmallDetail.api.descUrl) ? tmallDetail.api.descUrl : 'http:' + tmallDetail.api.descUrl,
					onload: function (res) {
						if (res.status !== 200) {
							console.error('获取详情失败')
						} else {
							var stringJson = res.responseText.replace(/^[^=]+=['"]?(.+)/, '$1').replace(/['";s]+$/, '')
							try {
								var json = JSON.parse(stringJson || '{}');
								callback(json.content)
							} catch (e) {
								callback(stringJson)
							}
						}
					}
				})
			},
			setTitle: function () {
				data.append('title', tmallDetail.itemDO.title);
			},
			setMetric: function () {
				data.append('metric', '件');
			},
			setBeginNumber: function () {
				data.append('beginNumber', 1);
			},
			setImages: function () {
				if (tmallDetail.propertyPics && tmallDetail.propertyPics.default) {
					tmallDetail.propertyPics.default.forEach(function (item, index) {
						if (index < 5) {
							data.append('smallpic' + (index + 1), /^http/.test(item) ? item : 'http:' + item);
						}
					})
				} else {
					$('#J_UlThumb').find('li').each(function (index) {
						if (index < 5) {
							var src = $(this).find('img').attr('src')
							data.append('smallpic' + (index + 1), /^http/.test(src) ? item : 'http:' + src);
						}
					})
				}

			},
			setPrice: function () {
				var property_value_list = [];
				if (tmallDetail.valItemInfo && tmallDetail.valItemInfo.skuList) {
					data.append('priceType', '3');
					tmallDetail.valItemInfo.skuList.forEach(function (item, index) {
						if (index > 49) {
							return false
						}
						property_value_list.push({
							'property': item.names,
							'price': tmallDetail.valItemInfo.skuMap[';' + item.pvs + ';'].price,
							'stock': tmallDetail.valItemInfo.skuMap[';' + item.pvs + ';'].stock,
							'picture': tmallDetail.propertyPics ? (item.pvs.split(';').filter(function (item) {
								return !!tmallDetail.propertyPics[';' + item + ';']
							}).map(function (item) {
								var url = tmallDetail.propertyPics[';' + item + ';'][0]
								return /^http/.test(url) ? url : 'http:' + url
							})[0] || '') : ''
						})
					})
					var temp = "[{\"name\": \"\", \"values\":" + JSON.stringify(property_value_list) + "}]"
					data.append('sellPropertyJson', temp);
				} else {
					data.append('priceType', '1');
					data.append('price00', 1);
					data.append('price03', $('.tm-price').html());
					data.append('salenum', $('#J_EmStock').html().replace(/[^d]/g, ''));
					data.append('perentCheck', '0');
					data.append('perentValue', '规格');
					data.append('childValue1', '混批');
				}

			},
			appendToSelector: '.tb-action.tm-clear'
		}
	}
	var importYwg = function () {

		data.append('alibabaVersion', version);
		data.append('freightTemplateId', freightTemplateId);
		data.append('marketCode', marketCode);
		data.append('userid', userid);
		data.append('alibabaToken', alibabaToken);
		data.append('deliveryPromise', '2');
		data.append('freightTemplateIdradio', freightTemplateIdradio);
		data.append('goodsflag', '1');
		data.append('isRefund', '0');
		data.append('productMode', '0');
		data.append('proimg3d', '1');
		// data.append('selltype', '1');
		data.append('source', '2');
		data.append('type', '1');
		data.append('OnlineOrderFlag', '1');
		//产品详情
		setSpecialData[location.host].setDetail(function (detail) {
			data.append('introduction', detail);
			//产品标题
			setSpecialData[location.host].setTitle()
			//产品标题
			setSpecialData[location.host].setMetric()
			setSpecialData[location.host].setBeginNumber()

			//设置图片
			setSpecialData[location.host].setImages()
			//判断定价类型
			setSpecialData[location.host].setPrice()
			// console.log({
			//   title: data.get('title'),
			//   detail: data.get('introduction'),
			//   images: [data.get('smallpic1'), data.get('smallpic2'), data.get('smallpic3'), data.get('smallpic4')],
			//   priceType: data.get('priceType'),
			//   priceRange:[[data.get('price00'),data.get('price10'),data.get('price20')], [data.get('price03'),data.get('price13'),data.get('price23')]],
			//   sellPropertyJson: JSON.parse(data.get('sellPropertyJson') || '{}')
			// })
			// return
			GM_xmlhttpRequest({
				method: "post",
				url: url,
				data: data,
				onload: function (res) {
					try {
						var json = JSON.parse(res.responseText || '{}')
						if (json.resultFlag) {
							alert('导入成功！\n即将进入产品发布页面对该产品编辑发布')
							window.location.href = json.redirect
						} else {
							alert(json.message || '导入失败');
						}
					} catch (e) {
						alert('您可能未登录您的义乌购商铺中心，\n点击确定后前往登录！');
						window.location.href = 'https://cas.yiwugo.com/cas/login?service=http%3A%2F%2Fwork.yiwugo.com%2F%2Findex.htm'
					}
				}
			});
		})
	}
	$('<button />').css({
		'border': 'none',
		'background-color': '#f90',
		'color': '#fff',
		'line-height': '40px',
		'width': '150px',
		'margin': '10px',
		'cursor': 'pointer',
		'font-size': '16px',
		'font-weight': '700',
		'position': 'fixed',
		'right': '100px',
		'bottom': '100px',
		'z-index': '2147483647'
	}).html('导入义乌购').click(function () {
		importYwg()
	}).hover(function () {
		$(this).css({
			'background-color': '#f60'
		})
	}, function () {
		$(this).css({
			'background-color': '#f90'
		})
	//}).appendTo($(setSpecialData[location.host].appendToSelector))
	}).appendTo($('body'))
}